package com.zzs.path.util;

import com.zzs.path.entity.Node;
import com.zzs.path.entity.Route;

import java.util.*;

public class RouteCacheUtils {

    // 两点间的 路径、距离 缓存
    public static Map<String, Route> routeCache = new HashMap<>();

    public static int key = -1;

    public static Route get( int startId, int endId ){

        Route route = null;

        String key = startId+"/"+endId;
        if((route = routeCache.get(key)) != null){ // 刚刚好

        }else if((route = routeCache.get(endId+"/"+startId)) != null) { // 正相反
            ArrayList<Integer> tempList = new ArrayList<>(route.getRouteList());
            Collections.reverse(tempList);
            route = new Route(route.getDistance(), tempList);
            route.setStartId(startId);
            route.setEndId(endId);
            //route.setId(getUniqueId());
            put(route);
        }

        return route;
    }

    public static void put(Route route){
        route.setId(getUniqueId());
        routeCache.put(route.getStartId()+"/"+route.getEndId(), route);
    }

    /**
     * 获取唯一id
     * @return 为了简单，直接根据顺序返回
     */
    public static int getUniqueId(){
        return key--;
    }

    // 打印路径缓存
    public static void printRouteCache(){
        System.out.println("\n===路径缓存routeCache===");
        Set<Map.Entry<String, Route>> entries = routeCache.entrySet();
        Iterator<Map.Entry<String, Route>> it = entries.iterator();
        while(it.hasNext()){
            Map.Entry<String, Route> next = it.next();
            System.out.println("routeCache："+next.getKey()+"："+next.getValue());
        }
    }


}
